<?php

namespace backend\modules\home\controllers;

use Yii;
use common\models\FrontUser;
use common\models\FrontLoginForm;
use frontend\models\SignupForm;
use backend\modules\home\models\FrontUserSearch;
use backend\modules\home\models\MhCustomerFile;
use backend\modules\home\models\MhCustomerProduct;
use common\components\Upload;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * FrontUserController implements the CRUD actions for FrontUser model.
 */
class FrontUserController extends Controller
{
    /**
     * @inheritdoc
     */
    public $enableCsrfValidation = false;
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all FrontUser models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new FrontUserSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single FrontUser model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        $model = $this->findModel($id);
        // 文件
        $file_model = MhCustomerFile::find()->where(['uid' => $id])->one();
        return $this->render('view', [
            'model' => $model,
            'file_model' => $file_model,
        ]);
    }

    /**
     * Creates a new FrontUser model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     * @throws \yii\base\Exception
     */
    public function actionCreate()
    {
        $model = new FrontUser();

        if ($postdata = Yii::$app->request->post(NULL)) {
            if(!$postdata['FrontUser']['username']){
                echo "<script>alert('用户名不能为空');window.history.go(-1)</script>";exit;
            }
            if(!$postdata['FrontUser']['email']){
                echo "<script>alert('邮箱不能为空');window.history.go(-1)</script>";exit;
            }
            if(!$postdata['FrontUser']['password_hash']){
                echo "<script>alert('密码不能为空');window.history.go(-1)</script>";exit;
            }

            $model = new SignupForm();
            $model->username = $postdata['FrontUser']['username'];
            $model->email = $postdata['FrontUser']['email'];
            $model->company_name = $postdata['FrontUser']['company_name'];
            $model->password = $postdata['FrontUser']['password_hash'];
            if (!$model->validate()) {
                $tmp_earr = $model->getFirstErrors();
                echo "<pre>";
                print_r($tmp_earr);exit;
            }
            if ($user = $model->signup()) {
                return $this->redirect(['index']);
            }
        }

        return $this->render('create', [
            'model' => $model,
        ]);
    }

    /**
     * Updates an existing FrontUser model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }

        return $this->render('update', [
            'model' => $model,
        ]);
    }

    public function actionUpload($id){
        $model = $this->findModel($id);
        if (Yii::$app->request->isPost) {
            // 删除旧文件
            $file = MhCustomerFile::find()->where([
                'uid' => $model->id,
            ])->one();
            if($file){
                $delete_path = getcwd() . $file->path;
                @unlink($delete_path);
                $file->delete();
            }
            $res = (new Upload)->uploadfilefront();
            if($res['code'] == 200){
                $file_model = new MhCustomerFile();
                $file_model->uid = $model->id;
                $file_model->path = $res['data'];
                $file_model->create_at = time();
                if(!$file_model->save()){
                    echo "<pre>";
                    print_r($file_model->errors);exit;
                }
            }
        }
        return $this->render('upload', [
            'model' => $model,
        ]);
    }

    /**
     * Deletes an existing FrontUser model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     * @throws \Throwable
     * @throws \yii\db\StaleObjectException
     */
    public function actionDelete($id)
    {
        $model = $this->findModel($id);

        if($model){
            // 删除授权书
            $file = MhCustomerFile::find()->where([
                'uid' => $model->id,
            ])->one();
            if($file){
                $delete_path = getcwd() . $file->path;
                @unlink($delete_path);
            }
            // 删除产品
            $list = MhCustomerProduct::find()->where([
                'uid' => $model->id,
            ])->all();
            if($list){
                foreach($list as $v){
                    $v->delete();
                }
            }
            $model->delete();
        }

        return $this->redirect(['index']);
    }

    public function actionResetPassword($id){
        $model = $this->findModel($id);
        if($postdata = Yii::$app->request->post()){
            if(!$postdata['FrontUser']['password_hash']){
                echo "<script>alert('密码不能为空');window.history.go(-1)</script>";exit;
            }
            // 加密
            $model->setPassword($postdata['FrontUser']['password_hash']);
            $model->save();
            return $this->redirect(['view', 'id' => $model->id]);
        }
        return $this->render('reset-password', [
            'model' => $model,
        ]);
    }

    /**
     * Finds the FrontUser model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return FrontUser the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = FrontUser::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
}
